package com.hsl.study.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsl.study.entities.User;
import com.hsl.study.service.UserService;
import com.hsl.study.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author 郝帅
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-02-18 08:46:53
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;
    @Resource
    private TransactionTemplate transactionTemplate;
    // 自定义耗时任务  且拼接字符串作为userID
    public String costTimeMethod(){
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return IdUtil.simpleUUID().substring(0,8);
    }
    @Override
    //开启事务
    @Transactional
    public int addUser(User user) {
        String userName = user.getUsername() + "-" + costTimeMethod();
        user.setUsername(userName);
        //插入数据库 成功返回
        return userMapper.insert(user);
    }

    @Override
    public int addUserOptimize(User user) {
        //开启事务拼接字符串+耗时任务
        String userName = user.getUsername()+"-"+costTimeMethod();
        user.setUsername(userName);
        //插入数据库 成功返回
        return transactionTemplate.execute(status -> userMapper.insert(user));
    }
}




